/*
 * TcpClient.h
 *
 *  Created on: 2016年5月13日
 *      Author: terry
 */

#ifndef TCPCLIENT_H_
#define TCPCLIENT_H_

#include "BasicType.h"
#include "Socket.h"
#include "TByteBuffer.h"
#include "SharedPtr.h"
#include <string>


namespace av
{

typedef std::shared_ptr< comn::ByteBuffer >		ByteBufferPtr;


class TcpClient
{
public:
    enum Event
    {
        kConnecting = 1,
        kConnected,
        kDisconnected
    };

    class Sink
    {
    public:
        virtual ~Sink() {}
        virtual void onTcpEvent(void* obj, int event) = 0;
    };

public:
	TcpClient();
	virtual ~TcpClient();

    bool connect(const std::string& ip, int port);
    void disconnect();

    bool isConnected();

    comn::Socket& getSocket();

    bool write(ByteBufferPtr& buffer);

    bool equals(const std::string& ip, uint16_t port) const;

    //void setWaterMark(int minSize, int maxSize);
    void setSendBuffer(int size);

    void setSink(Sink* sink);

    void enableReconnect(bool enabled);

protected:
    bool doConnect(const std::string& ip, uint16_t port);
    bool flushBuffer();

    void fireEvent(int event);

    int checkWriteClose(socket_t fd, int millsec);

    bool doWrite(ByteBufferPtr& buffer);

protected:
    std::string	m_ip;
    uint16_t	m_port;
    comn::Socket	m_socket;

    ByteBufferPtr	m_buffer;
    int		m_sendBufferSize;
    int		m_sentSize;	/// 缓冲区中已经发生字节数

    Sink*   m_sink;
    bool    m_connected;
    time_t  m_connectionTime;

    bool    m_connectionDropped;
    bool    m_reconnectEnabled;
};




} /* namespace av */

#endif /* TCPCLIENT_H_ */
